<?php

namespace App\Http\Controllers\Wechat;

use App\Events\Money\DepositEvent;
use App\Events\Ticket\BuyEvent;
use App\Events\Ticket\TicketDepositEvent;
use App\Http\Controllers\Common\Internal;
use App\Models\Order;
use App\Models\User;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 内部函数
 *
 */
class WechatPaymentController
{

    public function native(Request $request)
    {
        $config = config('wechat.payment');
        $payment = Factory::payment($config);
        $payMethod = $request->input('payMethod');
        $ticket = Internal::RechargeLogic($payMethod);
        $price = intval($payMethod);
        $outTradeNo = 'rysk'.date('YmdHis') . rand(1000, 9999);
        $user = $request->user();
        $orderData = [];
        $orderData['user_id'] = $user->id;
        $orderData['org_root'] = $user->org_root;
        $orderData['org_code'] = $user->org_code;;
        $orderData['orderno'] = $outTradeNo;
        $orderData['price'] = $price;
        $orderData['ticket'] = $ticket;
        $orderData['channel'] = 1;
        $orderData['created_at'] = date('Y-m-d H:i:s');
        Order::insert($orderData);
        $order = [
            'out_trade_no' => $outTradeNo, // 商户订单号，需保证唯一性
            'body' => '客户充值', // 商品描述
            'total_fee' => $price*100, // 订单总金额，单位为分
            'spbill_create_ip' => request()->ip(), // 客户端 IP 地址
            'notify_url' => $config['notify_url'], // 支付结果通知地址
            'trade_type' => 'NATIVE', // 交易类型，NATIVE 表示扫码支付
        ];
        $result = $payment->order->unify($order);
        if ($result['return_code'] === 'SUCCESS' && $result['result_code'] === 'SUCCESS') {
            $codeUrl = $result['code_url'];
            return response()->json([
                'code' => 200,
                'msg' => 'success',
                'data' => [
                    'url' => $codeUrl,
                    'order_no' => $outTradeNo
                ]
            ]);
        } else {
            return response()->json([
                'code' => -1,
                'msg' => 'error',
                'data' => null
            ]);

        }

    }

    public function notify()
    {
        $config = config('wechat.payment');
        $payment = Factory::payment($config);
        $payment->handlePaidNotify(function ($message, $fail) {
            // 验证订单是否已处理，避免重复处理
            // 这里可根据 $message['out_trade_no'] 查询本地订单记录进行判断
            // 处理支付成功逻辑，如更新订单状态等
            // 示例：更新订单状态为已支付
            $data = [];
            $data['value'] = json_encode($message);
            DB::table('text')->insert($data);
            $orderNumber = $message['out_trade_no'];
            $order =Order::where('orderno', $orderNumber)->where('status',0)->first();
            if($order){
                BuyEvent::dispatch($order->user_id, $order->ticket, sprintf("经办人 %s", '平台官方'));
                $user = User::find($order->user_id);
                $user->ticket += $order->ticket;
                $user->save();
                // 示例：更新订单状态为已支付
                Order::where('orderno', $orderNumber)->update(['status' => 1]);
            }
            return true;
        });
    }


}
